package com.util.vmwareops;

import com.vmware.vim25.mo.HostSystem;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

public class HostOps {
    public synchronized static List<HostInfo> updateHost(Connection con, ClusterInfo clusterInfo, HostSystem[] hosts, String versionId) throws SQLException {
        System.out.println(String.format("[INFO] Update host start"));

        List<HostInfo> hostInfo = new ArrayList<HostInfo>();

        Statement stmt = null;
        stmt = con.createStatement();

        for(HostSystem host : hosts) {
            if(! "connected".equals(host.getRuntime().getConnectionState().toString())) {
                continue;
            }
            HostInfo tmp = new HostInfo(
                    MyUtils.getUUID("HOST"),
                    host.getSummary().hardware.getUuid(),
                    host.getMOR().getVal(),
                    clusterInfo,
                    host.getName(),
                    host.getRuntime().getPowerState().toString(),
                    host.getRuntime().getConnectionState().toString(),
                    host.getSummary().hardware.numCpuCores,
                    host.getSummary().hardware.memorySize,
                    versionId
            );
            hostInfo.add(tmp);
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_host values(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d, %.2f, \"%s\")",
                    tmp.getId(),
                    tmp.getUuid(),
                    tmp.getDomainName(),
                    tmp.getCluster().getId(),
                    tmp.getName(),
                    tmp.getPowerState(),
                    tmp.getConnectState(),
                    tmp.getCpu(),
                    tmp.getMem(),
                    tmp.getVersionId()
            );
            // System.out.println(sql_command);
            stmt.execute(sql_command);
        }

        System.out.println(String.format("[INFO] Update host end"));
        return hostInfo;
    }

    public synchronized static void updateHostNetwork(Connection con, HostInfo hostInfo, List<NetworkInfo> networkInfos, String versionId) throws SQLException {
        Statement st = con.createStatement();
        for(NetworkInfo networkInfo : networkInfos) {
            String sql_command = String.format(
                    "insert into vsphere_host_network values(\"%s\", \"%s\", \"%s\")",
                    hostInfo.getId(),
                    networkInfo.getId(),
                    versionId
            );
            st.execute(sql_command);
        }
    }

    public synchronized static void updateHostDatastore(Connection con, HostInfo hostInfo, List<DatastoreInfo> datastoreInfos, String versionId) throws SQLException {
        Statement st = con.createStatement();
        for(DatastoreInfo datastoreInfo : datastoreInfos) {
            String sql_command = String.format(
                    "insert into vsphere_host_datastore values(\"%s\", \"%s\", \"%s\")",
                    hostInfo.getId(),
                    datastoreInfo.getId(),
                    versionId
            );
            st.execute(sql_command);
        }
    }
    public static Map<String, HostInfo> getHostInfoByVersionId(String versionId, Map<String, ClusterInfo> clusterInfos) throws InterruptedException {
        DBConnectionPool db = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = db.getConnection();
        Map<String, HostInfo> hostInfos = new HashMap<String, HostInfo>();
        String sql = String.format("select * from %s where version=\'%s\' and connect_state=\'connected\'", "resource_bundle_vsphere_host", versionId);
        try {
            Statement stmt = con.createStatement();
            ResultSet res = stmt.executeQuery(sql);
            if(res == null) {
                return null;
            }
            while(res.next()) {
                hostInfos.put(
                        res.getString("id"),
                        new HostInfo(
                                res.getString("id"),
                                res.getString("host_id"),
                                res.getString("host_domain_name"),
                                clusterInfos.get(res.getString("resource_bundle_vsphere_id")),
                                res.getString("name"),
                                res.getString("power_state"),
                                res.getString("connect_state"),
                                res.getInt("cpu"),
                                res.getDouble("memory_in_gb"),
                                res.getString("version")
                        )
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                db.close(con);
            }
        }
        return hostInfos;
    }
    public static Map<String, List<NetworkInfo>> getHostNetworkByVersionId(String versionId, Map<String, NetworkInfo> networkInfos) throws InterruptedException {
        DBConnectionPool db = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = db.getConnection();
        Map<String, List<NetworkInfo>> hostNetworkInfos = new HashMap<String, List<NetworkInfo>>();
        String sql = String.format("select * from %s where version=\'%s\'", "vsphere_host_network", versionId);
        try {
            Statement stmt = con.createStatement();
            ResultSet res = stmt.executeQuery(sql);
            if(res == null) {
                return null;
            }
            while(res.next()) {
                if(!hostNetworkInfos.containsKey(res.getString("host_id"))) {
                    hostNetworkInfos.put(res.getString("host_id"), new ArrayList<NetworkInfo>());
                }
                hostNetworkInfos.get(res.getString("host_id")).add(networkInfos.get(res.getString("network_id")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                db.close(con);
            }
        }
        return hostNetworkInfos;
    }


    public static Map<String, List<DatastoreInfo>> getHostDatastoreByVersionId(String versionId, Map<String, DatastoreInfo> datastoreInfos) throws InterruptedException {
        DBConnectionPool db = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = db.getConnection();
        Map<String, List<DatastoreInfo>> datastoreHostInfoMap = new HashMap<String, List<DatastoreInfo>>();
        String sql = String.format("select * from %s where version=\'%s\' and ", "vsphere_host_datastore", versionId);
        try {
            Statement stmt = con.createStatement();
            ResultSet res = stmt.executeQuery(sql);
            if(res == null) {
                return null;
            }
            while(res.next()) {
                if(!datastoreHostInfoMap.containsKey(res.getString("host_id"))) {
                    datastoreHostInfoMap.put(res.getString("host_id"), new ArrayList<DatastoreInfo>());
                }
                datastoreHostInfoMap.get(res.getString("host_id")).add(datastoreInfos.get(res.getString("datastore_id")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                db.close(con);
            }
        }
        return datastoreHostInfoMap;
    }
}
